﻿package com.eitb.programas.streaming{
	import flash.display.*;
	import flash.events.*;
	import flash.text.*;
	import flash.media.*;
	import flash.utils.*;
	import fl.controls.*;
	import fl.events.*;
	import flash.net.*;
	import flash.geom.*;

	import org.openvideoplayer.net.*;
	import org.openvideoplayer.events.*;

	import com.eitb.programas.streaming.literales.*;
	import com.eitb.programas.streaming.formatos.*;
	import com.eitb.literales.*;
	import com.eitb.bitmaps.*;
	import com.eitb.properties.*;
	import com.eitb.nielsen.*;
	import com.eitb.rutas.*;
	import com.eitb.imagenes.*;	
	
	public class ModeloStreaming implements IControladorStreaming {
		public static  const EITB_MUSIKA:String = "EITB Musika";
		public static  const EUSKADI_IRRATIA:String = "Euskadi Irratia";
		public static  const GAZTEA:String = "Gaztea";
		public static  const RADIO_EUSKADI:String = "Radio Euskadi";
		public static  const RADIO_VITORIA:String = "Radio Vitoria";
		public static  const CANAL_VASCO:String = "Canal Vasco";
		public static  const ETB_SAT:String = "ETB Sat";

		private var vStreaming:IVistaStreaming;
		private var literales:StreamingLiterales;
		// parametros
		private var formato:IVideoProperties;
		private var hostname:String;
		private var filename:String;
		private var imagen:String;
		//Marcado de Nielsen
		private var nielsenVideoCall:NielsenVideoCall;
		private var canal:String;

		private var connection:AkamaiConnection;
		private var stream:AkamaiNetStream;
		private var tRemaining:int;
		
		public function ModeloStreaming():void {

		}
		public function initNielsen(canal:String):void {
			this.nielsenVideoCall = new NielsenVideoCall("STREAMING", canal);
		}
		public function initVistaStreaming(vStreaming:IVistaStreaming):void {
			this.vStreaming = vStreaming;
		}
		public function initIdioma(idioma:int):void {
			this.literales=new StreamingLiterales(idioma);
		}
		public function initFormato(formato:IVideoProperties):void {
			this.formato = formato;
		}
		public function initHostname(hostname:String):void {
			this.hostname = hostname;
		}
		public function initFilename(filename:String):void {
			this.filename = filename;
		}
		public function initCanal(canal:String):void {
			this.canal = canal;
		}
		public function initAkamai():void {
			this.connection=new AkamaiConnection();
			this.connection.addEventListener(OvpEvent.ERROR,onError);
			this.connection.addEventListener(NetStatusEvent.NET_STATUS,netStatusHandler);
			// connect(AkamaiHostname:String, detectBandwidth:Boolean,createNetStream:Boolean, maxBufferLength:Number,useFastStartBuffer:Boolean, isLive:Boolean, port:String,protocol:String)
			this.connection.connect(this.hostname,true,true,4,true);
		}

		// CONTROLADOR STREAMING
		public function onResizeEvent(e:Event):void {
			if (StageDisplayState.FULL_SCREEN == this.vStreaming.getDisplayState()) {
				this.vStreaming.setVideoLocation(new Point(0,0));
				this.vStreaming.setVideoSize(this.vStreaming.getStageSize());
				this.vStreaming.showElements(false);
			} else {
				var vp:VideoProperties;
				vp = this.formato.getVideoProperties();
				this.vStreaming.showElements(true);
				this.vStreaming.setVideoLocation(new Point(vp.x,vp.y));
				this.vStreaming.setVideoSize(new Point(vp.width, vp.height));
			}
		}
		public function doMaximizeMinimize(e:MouseEvent):void {
			if (StageDisplayState.FULL_SCREEN == this.vStreaming.getDisplayState()) {
				this.vStreaming.setDisplayState(StageDisplayState.NORMAL);
			} else {
				this.vStreaming.setDisplayState(StageDisplayState.FULL_SCREEN);
			}
			this.vStreaming.dispatchStageEvent(new Event(Event.RESIZE));
		}
		
		public function volumeHandler(e:SliderEvent):void {
			stream.volume = e.target.value / 100;
		}
		// CONTROLADOR STREAMING
		private function connectedHandler():void {
			stream=new AkamaiNetStream(this.connection);
			// If the server requires us to subscribe to live streams, we need a few more event handlers
			if (this.connection.subscribeRequiredForLiveStreams) {
				stream.addEventListener(OvpEvent.SUBSCRIBED,subscribedHandler);
				stream.addEventListener(OvpEvent.UNSUBSCRIBED,unsubscribedHandler);
				stream.addEventListener(OvpEvent.SUBSCRIBE_ATTEMPT,subscribeAttemptHandler);
			}
			stream.addEventListener(OvpEvent.PROGRESS,progressHandler);
			stream.addEventListener(NetStatusEvent.NET_STATUS,netStreamStatusHandler);

			this.vStreaming.attachVideoNetStream(stream);
			this.vStreaming.setStatusDisplayText(literales.getLiteral(StreamingLiterales.EXITO_CONEXION));
			stream.play(this.filename);
			this.vStreaming.setVolumenSliderEnabled(true);
			stream.volume=.8;

			stream.addEventListener(NetStatusEvent.NET_STATUS,nsOnStatus);
		}
		// FIN NIELSEN

		private function nsOnStatus(event:NetStatusEvent):void {
			switch (event.info.code) {
				case "NetStream.Play.Start" :
					trace("Start");
					this.nielsenVideoCall.initTimer(new Timer(180000,0));
					break;
				case "NetStream.Play.Stop" :
					trace("stop");
					this.nielsenVideoCall.stopTimer();
					break;
			}
		}
		// Handles NetConnection status events. The description notifier is displayed
		// for rejection events.
		private function netStatusHandler(e:NetStatusEvent):void {
			trace('netStatusHandler' + e.info.code);

			switch (e.info.code) {
				case "NetConnection.Connect.Rejected" :
					trace("Rejected by server. Reason is " + e.info.description);
					break;
				case "NetConnection.Connect.Success" :
					connectedHandler();
					break;
			}
		}
		// Catches the netstream status events
		private function netStreamStatusHandler(e:NetStatusEvent):void {
			if (this.connection.subscribeRequiredForLiveStreams) {
				return;
			}
			switch (e.info.code) {
				case "NetStream.Play.Start" :
					subscribedHandler(null);
					break;
				case "NetStream.Play.Stop" :
					unsubscribedHandler(null);
					break;
			}
		}

		// Updates the UI elements as the  video plays
		private function progressHandler(e:OvpEvent):void {
			this.vStreaming.setTimeDisplayText(stream.timeAsTimeCode);
			this.vStreaming.setBufferDisplayVisible(stream.isBuffering);
			this.vStreaming.setBufferDisplayText(literales.getLiteral(StreamingLiterales.ALMACENADO) + stream.bufferPercentage + "%");
		}
		// Handles any errors dispatched by the connection class.
		private function onError(e:OvpEvent):void {
			trace("Error: " + e.data.errorDescription);
			this.vStreaming.setStatusDisplayText(literales.getLiteral(StreamingLiterales.FALLO) + e.data.errorDescription);
		}
		// Catches the subscription notification
		private function subscribedHandler(e:OvpEvent):void {
			trace("Subscribed");
			this.vStreaming.setBotonMaxMinEnabled(true);
			this.vStreaming.setStatusDisplayText(literales.getLiteral(StreamingLiterales.SUSCRITO));
		}
		// Catches the unsubscription notification
		private function unsubscribedHandler(e:OvpEvent):void {
			this.vStreaming.setStatusDisplayText(literales.getLiteral(StreamingLiterales.DADO_DE_BAJA));
			this.vStreaming.setBotonMaxMinEnabled(false);
			tRemaining=getTimer();
			trace("unsubscribed");
		}
		// Catches the subscribe attempt notification
		private function subscribeAttemptHandler(e:OvpEvent):void {
			trace("Subscribe Attempt");
			this.vStreaming.setStatusDisplayText(literales.getLiteral(StreamingLiterales.INTENTADO_SUSCRIPCION_) + new Number(stream.liveStreamMasterTimeout - Math.floor(getTimer() - tRemaining / 1000)).toString() + literales.getLiteral(StreamingLiterales._SEGUNDOS_LIMITES));
		}
	}
}